package com.le.bbs.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.le.bbs.dao.UserDao;
import com.le.bean.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

@Service
@Slf4j
public class JwtUserDetailsService implements UserDetailsService, UserService {
    @Autowired
    private UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String uname) throws UsernameNotFoundException {
        // 用于构建数据库查询条件
        QueryWrapper<User> wrapper = new QueryWrapper<>(); // ~
        // 设置查询条件，根据用户名来查询匹配的用户信息。
        wrapper.eq("uname", uname);
        User user = userDao.selectOne(wrapper);
        if (user != null){
            // Spring security 的 User类 （厉害！啥都包了                                                       // 这个是权限，现在传入的是空的权限列表
            return new org.springframework.security.core.userdetails.User(user.getUname(), user.getUpass(), new ArrayList<>());
        } else {
            throw  new UsernameNotFoundException("User not bbs with username: " + uname);
        }
    }

    @Override
    public User reg(User user) {
        userDao.insert(user);
        return user;
    }

    @Override
    public User findUserByUname(String uname) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("uname", uname);
        User user = userDao.selectOne(wrapper);
        return user;
    }

//
//    public static void main(String[] args) {
//        BCryptPasswordEncoder be = new BCryptPasswordEncoder();
//        System.out.println(be.encode("a"));
//    }
}
